package com.jdy.haoduoaiteacher.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jdy.haoduoaiteacher.Constant;
import com.jdy.haoduoaiteacher.MyTeacherApp;
import com.jdy.haoduoaiteacher.model.LeUser;
import com.jdy.haoduoaiteacher.util.AlertMessage;
import com.jdy.haoduoaiteacher.util.CommonUtil;
import com.jdy.haoduoaiteacher.util.CustomAsyncTask;
import com.jdy.haoduoaiteacher.util.LeConfig;
import com.jdy.haoduoaiteacher.util.Tools;
import com.jdy.haoduoai.view.visualizer.FrequencyDistributionBarView;
import com.jdy.haoduoaiteacher.widget.CustomOneBtnDialog;
import com.jdy.haoduoaiteacher.widget.LoadingDialog;
import com.ycsj.goldmedalnewconcept.R;

import org.droidparts.Injector;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

//import com.jdy.haoduoaiteacher.R;

/**
 * 
 * 
 * @author hf
 * 
 */
@SuppressLint({ "HandlerLeak", "Registered" })
public class BaseActivity extends FragmentActivity {

  private LinearLayout ly_content;
  private RelativeLayout ly_content1;
  private View contentView;
  public View titleLayout;
  protected ImageButton mBackImageButton;
  // protected View viewtittle_back_btn;
  private ProgressBar mProgressBarInTitle;
  protected TextView mTitleText, mTvUpright;
  protected ImageView img_upright; //, img_video;
  protected Button mUprightButton;
  protected Animation mPressedAnimation;
  protected LeUser mGlobalLeUser;
  protected FrequencyDistributionBarView device_view;
  private NetWorkChangeReciever mNetworkReciever;
  private DialogReceiver mDialogReceiver;

  private LoadingDialog loadingDialog;
  final private int DIALOG_LOADING = 100;
  private String strContent;

  public interface CancelLoadingDialogListener {
    public void onCancel();
  }

  public static Method mOverridePendingTransition;

  static {
    try {
      mOverridePendingTransition = Activity.class.getMethod(
          "overridePendingTransition",
          new Class[] { Integer.TYPE, Integer.TYPE });
      /* success, this is a newer device */
    } catch (NoSuchMethodException nsme) {
      /* failure, must be older device */
    }
  }

  @Override
  public void setContentView(int resId) {

    setContentViewWithoutInject(resId);
    // view inject
    Injector.inject(this);
  }

  public ProgressBar getProgressBar() {
    return mProgressBarInTitle;
  }

  public void setProgressBar(ProgressBar mProgressBar) {
    this.mProgressBarInTitle = mProgressBar;
  }

  public void notifyLoadingStart() {
    mProgressBarInTitle.setVisibility(View.VISIBLE);
  }

  public void notifyLoadingStop() {
    mProgressBarInTitle.setVisibility(View.GONE);
  }

  public void toastShow(final String message) {
    if (Tools.isNotNullStr(message)) {
      AlertMessage.show(this, message);
    }
  }

  public void closeInputMethod(IBinder token) {
    try {
      InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
      inputMethodManager.hideSoftInputFromWindow(token,
          InputMethodManager.HIDE_NOT_ALWAYS);

    } catch (Exception e) {
    }
  }

  public void openInputMethod(View view) {
    try {
      InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
      inputMethodManager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);

    } catch (Exception e) {
    }
  }

  @SuppressLint("InflateParams")
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    boolean isNeedOritation = getIntent().getBooleanExtra("isNeedOritation",
        false);
    if (!isNeedOritation) {
      setOrientation();
    }

    super.onCreate(savedInstanceState);

    titleLayout = LayoutInflater.from(this).inflate(R.layout.tittle_layout,
        null);
    mGlobalLeUser = MyTeacherApp.getInstance().getUserTeacher();
    mPressedAnimation = AnimationUtils.loadAnimation(this, R.anim.anim_pressed);
    mProgressBarInTitle = (ProgressBar) titleLayout
        .findViewById(R.id.progress_in_title);
    this.mBackImageButton = (ImageButton) titleLayout
        .findViewById(R.id.tittle_back_btn);
    this.device_view = (FrequencyDistributionBarView) titleLayout
        .findViewById(R.id.device_view);
    // this.viewtittle_back_btn = titleLayout
    // .findViewById(R.id.viewtittle_back_btn);
    this.mTitleText = (TextView) titleLayout.findViewById(R.id.tittle_name_txt);
    this.mUprightButton = (Button) titleLayout
        .findViewById(R.id.tittle_search_btn);

    mTvUpright = (TextView) titleLayout.findViewById(R.id.tv_upright);
    img_upright = (ImageView) titleLayout.findViewById(R.id.img_upright);
//    img_video = (ImageView) titleLayout.findViewById(img_video);
//    img_video.setOnTouchListener(CommonUtil.VIEW_TOUCH_DARK);
    mTvUpright.setOnTouchListener(CommonUtil.VIEW_TOUCH_DARK);
    img_upright.setOnTouchListener(CommonUtil.VIEW_TOUCH_DARK);

    this.mBackImageButton.setOnTouchListener(new OnTouchListener() {
      @SuppressLint("ClickableViewAccessibility")
      @Override
      public boolean onTouch(View v, MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
          mBackImageButton.setColorFilter(0x99c7c7c7,
              android.graphics.PorterDuff.Mode.MULTIPLY);
        } else if (event.getAction() == MotionEvent.ACTION_UP) {
          mBackImageButton.setColorFilter(null);
        }
        return false;
      }
    });

    this.mBackImageButton.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        finish();
        overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
      }
    });

    mNetworkReciever = new NetWorkChangeReciever();
    mDialogReceiver = new DialogReceiver();
  }

  protected FrequencyDistributionBarView getDeviceView() {
    return device_view;
  }

  @Override
  protected void onResume() {
    super.onResume();
    mGlobalLeUser = MyTeacherApp.getInstance().getUserTeacher();

    if (this instanceof LoginActivity) {

    } else {
      IntentFilter filter = new IntentFilter("com.remote.login");
      registerReceiver(mDialogReceiver, filter);
    }

    //
    // Intent intent = new Intent(this, DeviceMonitorService.class);
    // intent.putExtra("root_visiblity", View.GONE);
    // startService(intent);

  }

  @Override
  protected void onPause() {
    super.onPause();

    if (this instanceof LoginActivity) {

    } else {
      unregisterReceiver(mDialogReceiver);
    }

    // Intent intent = new Intent(this, DeviceMonitorService.class);
    // intent.putExtra("root_visiblity", View.GONE);
    // startService(intent);
  }

  @Override
  @Deprecated
  protected void onPrepareDialog(int id, Dialog dialog) {
    if (id == DIALOG_LOADING && dialog != null) {
      ((LoadingDialog) dialog).setDialogContent(strContent);
    }
    super.onPrepareDialog(id, dialog);
  }

  public void showloading(String str) {
    strContent = str;
    try {
      if (loadingDialog == null) {
        loadingDialog = createDialg();
      }

      if (loadingDialog != null) {
        loadingDialog.setDialogContent(strContent);
        if (!isFinishing()) {
          loadingDialog.show();
        }
      }
    } catch (Exception e) {
    }
  }

  public void showloading(String str, boolean canBeCancel) {
    strContent = str;
    try {
      if (loadingDialog == null) {
        loadingDialog = createDialg();
      }

      if (loadingDialog != null) {
        loadingDialog.setDialogContent(strContent);
        loadingDialog.setCancelable(canBeCancel);
        loadingDialog.setCanceledOnTouchOutside(canBeCancel);
        if (!isFinishing()) {
          loadingDialog.show();
        }
      }
    } catch (Exception e) {
    }
  }

  public void showloading(CustomAsyncTask async, String str,
                          CancelLoadingDialogListener li) {
    strContent = str;
    try {
      if (loadingDialog == null) {
        loadingDialog = createDialg();
      }

      if (loadingDialog != null) {
        loadingDialog.setAttachedAsyncTask(async);
        loadingDialog.setCancelLoadingDialogListener(li);
        loadingDialog.setDialogContent(strContent);
        if (!isFinishing()) {
          loadingDialog.show();
        }
      }
    } catch (Exception e) {
    }
  }

  // public void showloading(Subscription subs, String str,
  // CancelLoadingDialogListener li) {
  // strContent = str;
  // try {
  // if (loadingDialog == null) {
  // loadingDialog = createDialg();
  // }
  //
  // if (loadingDialog != null) {
  // loadingDialog.setAttachedSubscription(subs);
  // loadingDialog.setCancelLoadingDialogListener(li);
  // loadingDialog.setDialogContent(strContent);
  // if (!isFinishing()) {
  // loadingDialog.show();
  // }
  // }
  // } catch (Exception e) {
  // }
  // }

  public boolean isShowLoading() {
    if (loadingDialog != null) {
      return loadingDialog.isShowing();
    } else {
      return false;
    }
  }

  private LoadingDialog createDialg() {
    LoadingDialog dialog = new LoadingDialog(this, R.style.LoadingDialog);
    dialog.setCanceledOnTouchOutside(false);
    return dialog;
  }

  public void dismissLoading() {
    try {
      if (loadingDialog != null) {
        loadingDialog.dismiss();
        loadingDialog = null;
      }
    } catch (Exception e) {
    }
  }

  @Override
  public void onBackPressed() {
    super.onBackPressed();
    overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
  }

  protected void setOrientation() {
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
  }

  public Button getbtn_right() {
    return mUprightButton;
  }

  public ImageButton getImageBack() {
    return mBackImageButton;
  }

  public void setRightButtonVisible(int visible) {
    if (null != mUprightButton) {
      mUprightButton.setVisibility(visible);
    }
  }

  public void setTitle(String title) {
    if (null != mTitleText) {
      mTitleText.setText(title);
    }
  }

  public String getTitleStr() {
    return mTitleText.getText().toString();
  }

  @Override
  public void setTitle(CharSequence title) {
    if (null != mTitleText) {
      mTitleText.setText(title);
    }
  }

  @Override
  public void setTitle(int resId) {
    mTitleText.setText(getString(resId));
  }

  public void setTitle_BgColor(int color) {
    titleLayout.setBackgroundColor(color);
  }

  public void hideTitleView() {
    if (null != titleLayout) {
      titleLayout.setVisibility(View.GONE);
    }
  }

  public void showTitleView() {
    if (null != titleLayout) {
      titleLayout.setVisibility(View.VISIBLE);
    }
  }

  protected void showToastLong(Activity activity, final String result) {
    activity.runOnUiThread(new Runnable() {
      @Override
      public void run() {
        Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG)
            .show();
      }
    });
  }

  public void setContentViewWithoutInject(int resId) {
    if (ly_content1 != null) {
      ly_content1.removeAllViews();
    }
    LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    contentView = inflater.inflate(resId, null);
    ly_content1 = new RelativeLayout(this);
    ly_content1.setLayoutParams(new RelativeLayout.LayoutParams(
        RelativeLayout.LayoutParams.MATCH_PARENT,
        RelativeLayout.LayoutParams.MATCH_PARENT));
    titleLayout.setLayoutParams(new RelativeLayout.LayoutParams(
        RelativeLayout.LayoutParams.MATCH_PARENT,
        RelativeLayout.LayoutParams.WRAP_CONTENT));

    ly_content1.addView(titleLayout);
    View childView1 = ly_content1.getChildAt(0);
    RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
        LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
    lp.addRule(RelativeLayout.BELOW, childView1.getId());
    contentView.setLayoutParams(lp);
    ly_content1.addView(contentView);
    // RelativeLayout.LayoutParams lp1 = new RelativeLayout.LayoutParams(
    // LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    // lp1.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
    // buttomLayout.setLayoutParams(lp1);
    // ly_content1.addView(buttomLayout);
    setContentView(ly_content1);
  }

  // public void activityAnimUp() {
  // if (mOverridePendingTransition != null) {
  // try {
  // Activity activity = this.getParent();
  // if (activity == null) {
  // activity = this;
  // }
  // mOverridePendingTransition.invoke(activity, R.anim.activity_slide_up,
  // R.anim.activity_remain_stay);
  // } catch (InvocationTargetException ite) {
  // ite.printStackTrace();
  //
  // } catch (IllegalAccessException ie) {
  // ie.printStackTrace();
  //
  // } catch (Exception e) {
  // }
  // }
  // }
  //
  // public void activityAnimDown() {
  // if (mOverridePendingTransition != null) {
  // try {
  // Activity activity = this.getParent();
  // if (activity == null) {
  // activity = this;
  // }
  // mOverridePendingTransition.invoke(activity,
  // R.anim.activity_remain_stay, R.anim.activity_slide_down);
  // } catch (InvocationTargetException ite) {
  // ite.printStackTrace();
  //
  // } catch (IllegalAccessException ie) {
  // ie.printStackTrace();
  //
  // } catch (Exception e) {
  // }
  // }
  // }

  public void activityAnimFadeout() {
    if (mOverridePendingTransition != null) {
      try {
        Activity activity = this.getParent();
        if (activity == null) {
          activity = this;
        }
        mOverridePendingTransition.invoke(activity,
            R.anim.activity_remain_stay, R.anim.activity_fade_out);
      } catch (InvocationTargetException ite) {
        ite.printStackTrace();

      } catch (IllegalAccessException ie) {
        ie.printStackTrace();

      } catch (Exception e) {
      }
    }
  }

  public boolean isInputMethodVisible() {
    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    return imm.isActive();
  }

  public void enableNetworkChangeListener() {
    if (mNetworkReciever != null) {
      IntentFilter intentFilter = new IntentFilter();
      intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
      registerReceiver(mNetworkReciever, intentFilter);
    }
  }

  public void disableNetworkChangeListener() {
    if (mNetworkReciever != null) {
      try {
        unregisterReceiver(mNetworkReciever);
      } catch (IllegalArgumentException e) {

      }
    }
  }

  class DialogReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

      if (mCustomOneBtnDialog != null) {
        return;
      }

      CustomOneBtnDialog.Builder cdb = new CustomOneBtnDialog.Builder(
          getApplicationContext()).setTitle("下线通知")
          .setMessage("您的帐号已经在其它手机登录！如非本人操作，则密码可能已经泄露，建议修改密码后再重新登录。")
          .setPositiveButton("确定", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {

              LeConfig.isLogin = false;
//              LeConfig.isDeviceActivated = false;
//              LeConfig.isDeviceBinded = false;
              LeConfig.isReady = false;
              LeConfig.isDeviceConnect = false;
              // LeConfig.allowReconnSocket = false;
              // Const.connectF = 0;
              LeConfig.isDeviceOnline = 1;
              File dir = getFilesDir();
              File file1 = new File(dir, Constant.TELL_STORY_SERACH_FILE);
              file1.delete();
              File file2 = new File(dir, Constant.PUSH_STORY_SERACH_FILE);
              file2.delete();

              Intent toActivityIntent = new Intent(BaseActivity.this,
                  LoginActivity.class);
              toActivityIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
                  | Intent.FLAG_ACTIVITY_CLEAR_TASK);
              startActivity(toActivityIntent);
              dialog.dismiss();

              // TCPClient.instance().closeTCPSocket();
            }
          });
      mCustomOneBtnDialog = cdb.create();
      mCustomOneBtnDialog.getWindow().setType(
          WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
      mCustomOneBtnDialog.setCancelable(false);
      mCustomOneBtnDialog.setCanceledOnTouchOutside(false);
      mCustomOneBtnDialog.show();
    }

  }

  CustomOneBtnDialog mCustomOneBtnDialog;

  private class NetWorkChangeReciever extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
      String action = intent.getAction();

      ConnectivityManager connectivityManager = (ConnectivityManager) context
          .getSystemService(Context.CONNECTIVITY_SERVICE);
      NetworkInfo mobNetInfo = connectivityManager
          .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
      NetworkInfo wifiNetInfo = connectivityManager
          .getNetworkInfo(ConnectivityManager.TYPE_WIFI);

      if (mobNetInfo != null && !mobNetInfo.isConnected() && wifiNetInfo != null &&  !wifiNetInfo.isConnected()) {
        onNetworkDisconnect();
        return;
      }

      if (ConnectivityManager.CONNECTIVITY_ACTION.equals(action)
          && Tools.isNetworkAvailable2(BaseActivity.this)) {
        onNetworkAvailable(); // 网络可用
      }
    }
  }

  protected void onNetworkAvailable() {
  }

  protected void onNetworkDisconnect() {
    // toastShow("请检查网络连接");
  }

  public Handler handler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
      super.handleMessage(msg);
    }
  };

  // public void deleteExContentView() {
  // if (ly_content != null) {
  // ly_content.removeAllViews();
  // }
  // }

  public void setExContentView(View contentView) {

    LayoutParams layoutParams = new LayoutParams(LayoutParams.MATCH_PARENT,
        LayoutParams.MATCH_PARENT);
    contentView.setLayoutParams(layoutParams);
    if (ly_content == null) {
      ly_content = new LinearLayout(this);
      ly_content.setLayoutParams(new LinearLayout.LayoutParams(
          LinearLayout.LayoutParams.MATCH_PARENT,
          LinearLayout.LayoutParams.MATCH_PARENT));
      ly_content.setOrientation(LinearLayout.VERTICAL);
    } else {
      ly_content.removeAllViews();
    }
    ly_content.removeAllViews();
    ly_content.addView(titleLayout);
    if (contentView.getParent() != null) {
      ((ViewGroup) contentView.getParent()).removeView(contentView);
    }
    ly_content.addView(contentView);
    setContentView(ly_content);
  }

}
